package com.honghu.villagepost.activity.fragment

import android.os.Bundle
import androidx.recyclerview.widget.RecyclerView
import com.honghu.villagepost.activity.StoreDetailsActivity
import com.honghu.villagepost.adapter.StoreAdapter
import com.honghu.villagepost.api.ApiService
import com.honghu.villagepost.base.BaseListFragmet
import com.honghu.villagepost.callback.DialogCallback
import com.honghu.villagepost.callback.LzyResponse
import com.honghu.villagepost.constant.Constants
import com.honghu.villagepost.entity.Store
import com.lzy.okgo.model.Response

/**
 * 首页-附近商家列表
 */
class HomeNearShopFragment : BaseListFragmet<Store>() {

    private var shopType: Int = 0

    private val storeAdapter: StoreAdapter by lazy {
        StoreAdapter()
    }

    companion object {
        val DETAIL_REQUEST_CODE: Int = 1
        val SHOP_TYPE_HOME: Int = 0//首页-附件商家列表
        val SHOP_TYPE_VILLAGE: Int = 1//淘农村-附件商家列表
        fun newInstance(shopType: Int): HomeNearShopFragment {
            val fragment = HomeNearShopFragment()
            var bundle = Bundle()
            bundle.putInt(Constants.TYPE, shopType)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun getEnableRefresh(): Boolean {
        return false
    }

    override fun initData() {
        super.initData()

        if (arguments != null){
            shopType = arguments!!.getInt(Constants.TYPE, 0);
        }

        onRefresh(refreshLayout)
    }

    override fun bindRecyclerView(recLv: RecyclerView?) {
        storeAdapter.setOnItemClickListener { adapter, view, position ->
            var store = adapter.getItem(position) as Store
            StoreDetailsActivity.self(activity!!, store.id, 0)
        }
        recLv!!.adapter = storeAdapter
    }

    override fun loadData(page: Int, pageCount: Int) {
        ApiService.shop_list(this, shopType, page, object : DialogCallback<LzyResponse<Store>>() {
            override fun onSuccess(response: Response<LzyResponse<Store>>?) {
                onFinishRefresh()
                val records = response!!.body().data.records
                onGetDataSuc(records)
            }

            override fun onError(response: Response<LzyResponse<Store>>?) {
                super.onError(response)
                onFinishRefresh()
            }
        })
    }

    private fun onFinishRefresh() {
        if (parentFragment is HomeFragment) {
            (parentFragment as HomeFragment).onFinishRefresh()
        }
    }

    override fun getData(): MutableList<Store> {
        return storeAdapter.data
    }

    override fun bindData(isRefresh: Boolean, list: MutableList<Store>?) {
        if (isRefresh) storeAdapter.setNewData(list) else storeAdapter.addData(list!!)
    }

    fun setEnableRefresh(enableRefresh: Boolean) {
    }

    fun onAutoRefresh() {
        onRefresh(refreshLayout)
    }
}